package com.app.island.cash.requestrisk.newwork

import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL

/**
 * 统计错误信息
 */
object StatisticLogManage {
    @Throws(Exception::class)
    fun statisticLog(requestUrl: String, reqParamStr: String, signMsgStr: String): String {
        LogUtil.e(requestUrl)
        LogUtil.e("reqParamStr: " + reqParamStr)
        LogUtil.e("signMsgStr: " + signMsgStr)
        var result: String? = ""
        val conn: HttpURLConnection
        val url: URL = URL(requestUrl)
        conn = url.openConnection() as HttpURLConnection

        // 设置允许输出
        conn.setDoOutput(true)
        conn.setDoInput(true)
        // 设置不用缓存
        conn.setUseCaches(false)
        conn.setRequestProperty("signMsg", signMsgStr)
        // 设置传递方式
        conn.setRequestMethod("POST")
        // 设置维持长连接
        conn.setRequestProperty("Connection", "Keep-Alive")
        // 设置文件字符集:
        conn.setRequestProperty("Charset", "UTF-8")
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
        conn.setRequestProperty(
            "Content-Length",
            reqParamStr.toByteArray().size.toString() + ""
        ) //设置文件请求的长度  
        conn.setReadTimeout(180 * 1000) //设置读取超时时间          
        conn.setConnectTimeout(120 * 1000) //设置连接超时时间      
        val out: OutputStream = conn.getOutputStream()
        out.write(reqParamStr.toByteArray())
        out.flush()
        out.close()
        if (conn.getResponseCode() == 200) {
            val inputStream: InputStream = conn.getInputStream()
            val b: ByteArray = ByteArray(1024)
            var len: Int = 0
            // 创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
            val bos: ByteArrayOutputStream = ByteArrayOutputStream()
            while ((inputStream.read(b).also({ len = it })) != -1) {
                bos.write(b, 0, len)
            }
            // 把字节数组输出流的数据转换成字节数组
            result = String(bos.toByteArray(), charset("utf-8"))
        } else {
            throw HttpStateException(conn.getResponseCode().toString())
        }
        conn.disconnect()
        return result
    }

    class HttpStateException internal constructor(exception: String?) : Exception(exception)
}